//
//  AppConfig.m
//  helper
//
//  Created by huangyi on 12-11-20.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "JSONObj.h"
#import "NSString+path.h"
#import "NSData+utils.h"
#import "NSDictionary+utils.h"

@interface JSONObj()

@property(nonatomic,strong)NSString *file;
@property(nonatomic,strong)NSMutableDictionary *store;

@end

@implementation JSONObj

-(void)dealloc{
    [self save];
}
-(JSONObj*)init{
    return [self initJSON:nil];
}
+(JSONObj*)shared{
    static JSONObj *singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filename=@"app.json".docPath;
        singleton=[[JSONObj alloc] initJSON:filename];
    });
    return singleton;
}
-(id)initJSON:(NSString*)filename{
    self=[super init];
    if (self) {
        self.file=[NSString stringWithString:filename];
        [self reload];
    }
    return self;
}
-(NSString*)absolutePath{
    return self.file;
}

-(id)key:(NSString*)key{
    id value=nil;
    if (key) {
        value=[self.store valueForKey:key];
    }
    return value;
}
-(BOOL)key:(NSString*)key value:(id)value{
    if (key) {
        if (value) {
            [self.store setValue:value forKey:key];
        }else{
            [self.store removeObjectForKey:key];
        }
        return YES;
    }else{
        return NO;
    }
}

-(BOOL)save{
    NSData *json=[self.store jsonData];
    return [json writeToFile:self.file atomically:YES];
}
-(BOOL)clear{
    [self.store removeAllObjects];
    return [self save];
}

-(void)reload{
    self.store=[NSMutableDictionary dictionary];
    if (self.file) {
        if (self.file.isFile) {
            NSData *json=[NSData dataWithContentsOfFile:self.file];
            [self.store setValuesForKeysWithDictionary:[json jsonObject]];
        }else{
            [self save];
        }
    }
}

@end
